﻿using CommonDevelop;
using CommonDevelop.Operator;
using CommonEngine;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net.Http.Headers;
using WebAdmin.Models;

namespace WebAdmin.Controllers
{
    /// <summary>
    /// 工作环境
    /// </summary>
    public class WorkDoneController : Controller
    {
        private readonly IPathProvider pathProvider;
        /// <summary>
        /// 构造
        /// </summary>
        public WorkDoneController(IPathProvider pathProvider)
        {
            this.pathProvider = pathProvider;
        }

        /// <summary>
        /// 地区级联
        /// </summary>
        [HttpGet]
        [Authorize(Policy = AuthPolicy.CHECK)]
        public ActionResult Distpicker()
        {
            ViewBag.Title = "distpicker";
            return View();
        }

        /// <summary>
        /// 404
        /// </summary>
        public IActionResult Error404()
        {
            ViewBag.Title = "404";
            return View();
        }

        /// <summary>
        /// 测试error
        /// </summary>
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error(int id)
        {
            int code = id;
            ViewBag.Title = "Error";
            if (code == 401)
                return RedirectToAction("Login", "Login");  //验证失败
            else if (code == 403)   //API环境中重新配置
                return Json(new ResponseParameter { code = ResponseCode.fail, info = "未授权" });
            else if (code == 404)   //API环境中重新配置
                return RedirectToAction("Error404", "WorkDone");
            else
                return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, code = code });
        }

        #region---接收富文本的上传图片---

        string originalName = null;
        int uploadFileLength = 0;

        [HttpPost]
        [DisableRequestSizeLimit]
        public ContentResult Upload_UEditor()
        {
            //最大文件大小
            int maxSize = 10 * 1024 * 1024;
            //定义允许上传的文件扩展名
            string extStr = "gif,jpg,jpeg,png,bmp";
            if (Request.Form.Files.Count > 0)
            {
                //文件保存目录路径
                string savePath = "/Enc/Uploads/";
                //文件保存目录URL
                string saveUrl = this.pathProvider.GetHostUri(this.Request) + savePath;

                var imgFile = Request.Form.Files[0];
                if (imgFile == null)
                    return showError("请选择文件");

                this.originalName = ContentDispositionHeaderValue
                                .Parse(imgFile.ContentDisposition)
                                .FileName
                                .Trim('"');
                string fileExt = Path.GetExtension(imgFile.FileName).ToLower(); //文件扩展名
                long fileSize = imgFile.Length; //获得文件大小，以字节为单位
                if (fileSize > maxSize)
                    return showError("上传文件大小超过限制。");

                if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(extStr.Split(','), fileExt.Substring(1).ToLower()) == -1)
                    return showError("上传文件扩展名是不允许的扩展名。\n只允许" + extStr + "格式。");

                string dirPath = this.pathProvider.MapPath(savePath);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                //创建文件夹
                dirPath += "image\\";
                saveUrl += "image\\";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
                dirPath += ymd + "\\";
                saveUrl += ymd + "\\";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
                string filePath = dirPath + newFileName;

                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    imgFile.CopyTo(fs);
                    fs.Flush();
                }

                string fileUrl = saveUrl + newFileName;
                return showOk(fileUrl);
            }

            return showError("请选择文件");
        }
        private ContentResult showOk(string fileUrl)
        {
            Hashtable infoList = new Hashtable();
            infoList.Add("state", "SUCCESS");
            infoList.Add("url", fileUrl);
            infoList.Add("originalName", originalName);
            infoList.Add("name", Path.GetFileName(fileUrl));
            infoList.Add("size", uploadFileLength);
            infoList.Add("type", Path.GetExtension(originalName));
            return Content(JsonHelper.SerializeObject(infoList));
        }
        private ContentResult showError(string message)
        {
            Hashtable infoList = new Hashtable();
            infoList.Add("state", message);
            infoList.Add("url", "");
            infoList.Add("originalName", originalName);
            infoList.Add("name", "");
            infoList.Add("size", uploadFileLength);
            infoList.Add("type", Path.GetExtension(originalName));
            return Content(JsonHelper.SerializeObject(infoList));
        }

        #endregion

        #region---上传图片---

        //最大文件大小
        int maxSize = 20 * 1024 * 1024;
        //定义允许上传的文件扩展名
        string extStr = "gif,jpg,jpeg,png,bmp";

        /// <summary>
        /// 上传图片
        /// </summary>
        [HttpPost]
        public JsonResult UploadPic()
        {
            if (Request.Form.Files.Count > 0)
            {
                //-----准备文件夹----
                string savePath = "/Enc/Uploads/";
                string saveUrl = this.pathProvider.GetHostUri(this.Request) + savePath;
                string dirPath = this.pathProvider.MapPath(savePath);
                if (!Directory.Exists(dirPath))
                {
                    bool t; //文件夹不存在就新建文件夹
                    this.pathProvider.CreateFolder(savePath, false, out t);
                }

                if (Request.Form.Files.Count == 1)
                {
                    IFormFile file = Request.Form.Files[0];
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(extStr.Split(','), fileExt.Substring(1).ToLower()) == -1)
                        return Json(new { status = false, url = "", msg = "上传文件扩展名是不允许的扩展名。\n只允许" + extStr + "格式。" });

                    if (file == null || file.Length > maxSize)
                        return Json(new { status = false, url = "", msg = "上传文件大小超过限制" });

                    if (file.Length > 0)
                    {
                        string title = string.Empty;
                        title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);

                        using (FileStream fs = System.IO.File.Create(dirPath + title))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                        //返回的应该是图片的网站地址
                        return Json(new { status = true, url = saveUrl + title });
                    }
                }
                else
                {
                    List<string> urllist = new List<string>();
                    var files = Request.Form.Files;
                    foreach (var file in files)
                    {
                        string fileExt = Path.GetExtension(file.FileName).ToLower();
                        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(extStr.Split(','), fileExt.Substring(1).ToLower()) == -1)
                            return Json(new { status = false, url = "", msg = "上传文件扩展名是不允许的扩展名。\n只允许" + extStr + "格式。" });

                        if (file == null || file.Length > maxSize)
                            return Json(new { status = false, url = "", msg = "上传文件大小超过限制" });

                        if (file.Length > 0)
                        {
                            string title = string.Empty;
                            title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);
                            using (FileStream fs = System.IO.File.Create(dirPath + title))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            //返回的应该是图片的网站地址
                            urllist.Add(saveUrl + title);
                        }
                    }
                    return Json(new { status = true, url = urllist.ToArray() });
                }
            }
            else
            {
                return Json(new { status = false, url = "", msg = "请选择文件" });
            }

            return Json(new { status = false, url = "", msg = "" });
        }
        /// <summary>
        /// 上传图片---生成缩略图
        /// </summary>
        [HttpPost]
        public JsonResult UploadPicBit()
        {
            if (Request.Form.Files.Count > 0)
            {
                //-----准备文件夹----
                string savePath = "/Enc/Uploads/";
                string saveUrl = this.pathProvider.GetHostUri(this.Request) + savePath;
                string dirPath = this.pathProvider.MapPath(savePath);
                if (!Directory.Exists(dirPath))
                {
                    bool t; //文件夹不存在就新建文件夹
                    this.pathProvider.CreateFolder(savePath, false, out t);
                }

                if (Request.Form.Files.Count == 1)
                {
                    IFormFile file = Request.Form.Files[0];
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(extStr.Split(','), fileExt.Substring(1).ToLower()) == -1)
                        return Json(new { status = false, url = "", msg = "上传文件扩展名是不允许的扩展名。\n只允许" + extStr + "格式。" });

                    if (file == null || file.Length > maxSize)
                        return Json(new { status = false, url = "", msg = "上传文件大小超过限制" });

                    if (file.Length > 0)
                    {
                        string title = string.Empty;
                        title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);
                        var path = dirPath + title;
                        using (FileStream fs = System.IO.File.Create(path))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                        Bit(path);
                        //返回的应该是图片的网站地址
                        return Json(new { status = true, url = saveUrl + title });
                    }
                }
                else
                {
                    List<string> urllist = new List<string>();
                    var files = Request.Form.Files;
                    foreach (var file in files)
                    {
                        string fileExt = Path.GetExtension(file.FileName).ToLower();
                        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(extStr.Split(','), fileExt.Substring(1).ToLower()) == -1)
                            return Json(new { status = false, url = "", msg = "上传文件扩展名是不允许的扩展名。\n只允许" + extStr + "格式。" });

                        if (file == null || file.Length > maxSize)
                            return Json(new { status = false, url = "", msg = "上传文件大小超过限制" });

                        if (file.Length > 0)
                        {
                            string title = string.Empty;
                            title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);
                            var path = dirPath + title;
                            using (FileStream fs = System.IO.File.Create(path))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            Bit(path);
                            //返回的应该是图片的网站地址
                            urllist.Add(saveUrl + title);
                        }
                    }
                    return Json(new { status = true, url = urllist.ToArray() });
                }
            }
            else
            {
                return Json(new { status = false, url = "", msg = "请选择文件" });
            }

            return Json(new { status = false, url = "", msg = "" });
        }
        public void Bit(string filename)
        {
            Size sizeView = new Size(200, 200);
            Bitmap tmpBmp = new Bitmap(sizeView.Width, sizeView.Height);
            Graphics g = Graphics.FromImage(tmpBmp);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Rectangle destRect = new Rectangle(0, 0, sizeView.Width, sizeView.Height);
            Rectangle srcRect;
            string[] filetypeList = new string[] { "*.jpg", "*.jpeg", "*.png", "*.bmp" };
            try
            {
                var filetype = "*" + Path.GetExtension(filename);
                System.Drawing.Imaging.ImageFormat format;
                if (filetype.Equals(filetypeList[0]) || filetype.Equals(filetypeList[1]))
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                else if (filetype.Equals(filetypeList[2]))
                    format = System.Drawing.Imaging.ImageFormat.Png;
                else if (filetype.Equals(filetypeList[3]))
                    format = System.Drawing.Imaging.ImageFormat.Bmp;
                else
                    return;

                Image srcImg = Image.FromFile(filename);
                g.Clear(Color.White);
                srcRect = new Rectangle(0, 0, srcImg.Width, srcImg.Height);
                g.DrawImage(srcImg, destRect, srcRect, GraphicsUnit.Pixel);
                srcImg.Dispose();
                tmpBmp.Save(filename);
            }
            catch
            {

            }
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        public static MemoryStream Compress(Stream fileStream, long quality)
        {
            try
            {
                using (Image img = Image.FromStream(fileStream))
                {
                    using (Bitmap bitmap = new Bitmap(img))
                    {
                        ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
                        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                        EncoderParameters myEncoderParameters = new EncoderParameters(1);
                        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
                        myEncoderParameters.Param[0] = myEncoderParameter;

                        var ms = new MemoryStream();
                        bitmap.Save(ms, CodecInfo, myEncoderParameters);
                        myEncoderParameters.Dispose();
                        myEncoderParameter.Dispose();
                        ms.Position = 0;
                        return ms;
                    }
                }
            }
            catch (Exception)
            {
                return new MemoryStream(StreamToBytes(fileStream));
            }
        }
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
        private static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        #endregion
    }
}
